<?php

namespace liketp\response;

use liketp\Response;
use liketp\App;

class View extends Response
{
    protected $contentType = 'text/html';
    protected $tpl = '';
    protected $isTplContent = false;

    protected $app;
    protected $viewEngine = null;

    public function __construct(App $app, $data, int $code)
    {
        $this->init($data, $code);
        $this->app = $app;
        $this->viewEngine = $this->createViewEngine();
    }

    public function output($data)
    {
        $this->viewEngine->tpl($this->tpl, $this->isTplContent)->data($data ?? []);
        $content = $this->viewEngine->render();
        return $content;
    }

    public function tpl(?string $tpl = null)
    {
        if (is_null($tpl)) {
            $req = $this->app->request;
            $tpl = $this->resolveTpl($req->controller(), $req->action());
        }
        $this->tpl = $this->app->getViewPath() . $tpl;
        return $this;
    }

    public function isTplContent(bool $isTplContent = false)
    {
        $this->isTplContent = $isTplContent;
        return $this;
    }

    public function __call($method, $args)
    {
        return call_user_func_array([$this->viewEngine, $method], $args);
    }


    //------------------------------------------------ protected
    protected function createViewEngine()
    {
        $engine = config('view.engine', 'php_native');
        $engineClass = 'liketp\\view\\' . str_to_camel($engine, true);
        return app($engineClass);
    }

    protected function resolveTpl($controller, $action)
    {
        $controller = explode('.', $controller);
        $pathItems = array_merge($controller, [$action]);
        return implode(DS, $pathItems);
    }
}
